<template>
  <div>
    <!-- 导航菜单 -->
    <DwMenu/>
    <main class="ml-64 flex-1 p-6">
      <div class="container-fluid" style="margin: 40px 20px 20px ">
        <h2>系统参数配置</h2>

        <!-- 搜索区域 -->
        <el-form inline>
          <el-form-item label="参数说明">
            <el-input v-model="searchQuery" clearable placeholder="按参数说明搜索" @clear="onSearchClear"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="reloadTable">刷新</el-button>
          </el-form-item>
        </el-form>

        <!-- 参数表格 -->
        <el-table :data="paginatedConfigData" stripe style="width: 100%">
          <el-table-column label="ID" prop="id" width="60"/>
          <el-table-column label="参数说明" prop="config"/>
          <el-table-column label="值" prop="value">
            <template slot-scope="scope">
              {{ scope.row.value.length > 30 ? scope.row.value.slice(0, 30) + '...' : scope.row.value }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button size="mini" @click="editConfig(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            :current-page.sync="currentConfigPage"
            :page-size="pageSize"
            :total="filteredConfig.length"
            background
            layout="prev, pager, next"
            @current-change="onConfigPageChange"
        />


        <!-- 修改记录表格 -->
        <h2>修改记录</h2>
        <el-table :data="paginatedRecordData" stripe style="width: 100%">
          <el-table-column label="ID" prop="id" width="60"/>
          <el-table-column label="旧值" prop="jz"/>
          <el-table-column label="新值" prop="xz"/>
          <el-table-column label="修改时间" prop="xgsj">
            <template slot-scope="scope">
              {{ luodeng(scope.row.xgsj) }}
            </template>
          </el-table-column>
          <el-table-column label="参数代码" prop="csdm"/>
          <el-table-column label="参数说明" prop="cssm"/>
          <el-table-column label="修改人" prop="xgr"/>
        </el-table>

        <el-pagination
            :current-page.sync="currentRecordPage"
            :page-size="pageSize"
            :total="recordData.length"
            background
            layout="prev, pager, next"
            @current-change="onRecordPageChange"
        />
      </div>
    </main>
  </div>
</template>

<script>
import DwMenu from '@/components/admin/Admin_menu.vue';
import axios from 'axios';

export default {
  name: 'ParameterConfig',
  components: {DwMenu},
  data() {
    return {
      searchQuery: '',
      configData: [],
      recordData: [],
      pageSize: 10,
      currentConfigPage: 1,
      currentRecordPage: 1
    };
  },
  computed: {
    filteredConfig() {
      const q = this.searchQuery.trim().toLowerCase();
      return this.configData.filter(item => item.config && item.config.toLowerCase().includes(q));
    },
    paginatedConfigData() {
      const start = (this.currentConfigPage - 1) * this.pageSize;
      return this.filteredConfig.slice(start, start + this.pageSize);
    },
    paginatedRecordData() {
      const start = (this.currentRecordPage - 1) * this.pageSize;
      return this.recordData.slice(start, start + this.pageSize);
    }
  },
  methods: {
    luodeng(time) {
      const date = new Date(time); // 自动转换为本地时间

      return (
          date.getFullYear() + '-' +
          String(date.getMonth() + 1).padStart(2, '0') + '-' +
          String(date.getDate()).padStart(2, '0') + ' ' +
          String(date.getHours()).padStart(2, '0') + ':' +
          String(date.getMinutes()).padStart(2, '0') + ':' +
          String(date.getSeconds()).padStart(2, '0')
      );
    },
    loadConfigData() {
      axios.get('/config/getAllConfig')
          .then(res => {
            this.configData = res.data.data || [];
          })
          .catch(err => console.error('获取配置失败：', err));
    },
    loadRecordData() {
      axios.get('/config/getAllCsxgjl')
          .then(res => {
            this.recordData = res.data.data || [];
          })
          .catch(err => console.error('获取修改记录失败：', err));
    },
    reloadTable() {
      this.currentConfigPage = 1;
      this.loadConfigData();
      this.currentRecordPage = 1;
      this.loadRecordData();
    },
    onSearchClear() {
      this.currentConfigPage = 1;
    },
    onConfigPageChange(page) {
      this.currentConfigPage = page;
    },
    onRecordPageChange(page) {
      this.currentRecordPage = page;
    },
    editConfig(row) {
      // 使用全局注入的 $UserInfo
      const username = this.$UserInfo ? this.$UserInfo.username : '';
      this.$prompt('请输入新值', '修改参数', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputValue: row.value
      }).then(({value}) => {
        const form = new FormData();
        form.append('id', row.id);
        form.append('value', value);
        form.append('xnyh', username);
        form.append('xnyhsfdm', '1');

        axios.post('/config/updateConfigByMybatisXml', form)
            .then(res => {
              if (res.data.result) {
                this.$message.success('修改成功');
                this.currentConfigPage = 1;
                this.currentRecordPage = 1;
                this.loadConfigData();
                this.loadRecordData();
              } else {
                this.$message.error('失败：' + res.data.msg);
              }
            })
            .catch(err => {
              this.$message.error('请求失败：' + err.message);
            });
      }).catch(() => {
      });
    }
  },
  created() {
    this.loadConfigData();
    this.loadRecordData();
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.box-card {
  margin-bottom: 30px;
}
</style>
